在小專案裡,用 props 傳資料、emit 傳事件就夠。
但隨著專案變大,不同元件之間要共用資料(例如:玩家登入狀態、星艦燃料存量、背包物品),props 傳來傳去會變成災難。
⭢這時候就需要「全域資料倉庫」,Pinia 就是 Vue 3 官方推薦的能量核心。
npm install pinia
2.在 main.js
掛上:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
src/stores/ship.js
:import { defineStore } from 'pinia'
export const useShipStore = defineStore('ship', {
state: () => ({
fuel: 100,
hp: 80,
shield: true
}),
actions: {
consumeFuel(amount) {
this.fuel -= amount
},
repair() {
this.hp = 100
}
},
getters: {
isDamaged: (state) => state.hp < 100
}
})
<script setup>
import { useShipStore } from '../stores/ship'
const ship = useShipStore()
function travel() {
ship.consumeFuel(10)
}
</script>
<template>
<div>
<p>燃料:{{ ship.fuel }}</p>
<p>血量:{{ ship.hp }}({{ ship.isDamaged ? '受損' : '完好' }})</p>
<button @click="travel">🌌 啟航</button>
</div>
</template>
1.state → 儲存共享資料(像燃料槽)。
2.actions → 修改資料的方式(像操作控制台)。
3.getters → 基於 state 的計算屬性(像狀態燈號)。
4.store → 不同模組的能量核心,可在各元件隨時呼叫。
⭢Pinia 讓我們把狀態集中,避免資料在元件間傳來傳去,專案會更乾淨、邏輯更清楚。
參考資源
https://vuejs.org/guide
https://www.runoob.com/vue3